/**
 * @product: PCDC-CMS
 * @copyright: FSAI-南征北战信息科技
 * @filename: com.ruoyi.cmsbiz.util.BeanUtilsTool.java
 *
 * @link: Http://www.fastsai.com
 * @jdkv: Jdk 1.8
 */
package com.fsai.cms.util;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;

/**
 * bean和map互转-apache性能没beanmap好
 * 
 * @project: pcdc-cms-biz
 *
 * @author: JaffeHe
 * @email: JaffeHe@foxmail.com
 * @date: 2021-03-11 16:01
 *
 * @ChangeLog<br/>
 * 				Developer Date Comment <br/>
 */
public class BeanUtilsTool {

	public static <T> Map<String, String> beanToMap(T bean)
			throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
		return BeanUtils.describe(bean);
	}

	public static <T> T mapToBean(Map<String, Object> map, Class<T> bean)
			throws IllegalAccessException, InstantiationException, InvocationTargetException {
		T t = bean.newInstance();
		BeanUtils.populate(t, map);
		return t;
	}

	//sql-Map值转换bean
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T> T sqlMapToBean(Map<String, Object> map, Class<T> bean)
			throws IllegalAccessException, InstantiationException, InvocationTargetException {
		Map re_map = new HashMap();
		if (re_map != null) {
			Iterator var2 = map.entrySet().iterator();
			while (var2.hasNext()) {
				Entry<String, Object> entry = (Entry) var2.next();
				re_map.put(lineToHump((String) entry.getKey()), map.get(entry.getKey()));
			}
		}

		T t = bean.newInstance();
		BeanUtils.populate(t, re_map);
		return t;
	}

	private static Pattern humpPattern = Pattern.compile("[A-Z]");

	/** 驼峰转下划线 */
	public static String humpToLine(String str) {
		Matcher matcher = humpPattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	private static Pattern linePattern = Pattern.compile("_(\\w)");

	/** 下划线转驼峰 */
	public static String lineToHump(String str) {
		str = str.toLowerCase();
		Matcher matcher = linePattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

}
